
var express = require('express');
var app = express();
var multer = require('multer');
var path = require('path');
const cors = require('cors');
var routes=require('./route/route');
var bodyParser = require('body-parser');//解析请求
var cookieParser = require('cookie-parser'); //解析cookie
var jwt = require("jsonwebtoken")
const rateLimiter = require('express-rate-limit');
const limiter = rateLimiter({
    windowMs: 60 * 1000, // 1分钟
    max: 100, // 最大请求数量
    message: '请求过于频繁，请稍后再试。'
})
//撒盐，加密时候混淆
var secret = '123bingjspoiuytrewqlkjhgfdsa'
//生成token
//info也就是payload是需要存入token的信息
function createToken(info) {
    let token = jwt.sign(info, secret, {
        //Token有效时间 单位s
        expiresIn:60 * 60 * 100
    })
    return token
}

//验证Token
function verifyToken(token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, secret, (error, result) => {
            if(error){
                reject(error)
            } else {
                resolve(result)
            }
      })
    })
} 
app.use(function(req, res, next) {
    //指定允许其他域名访问 *所有
    res.setHeader("Access-Control-Allow-Origin", "*");
    //允许客户端请求头中带有的
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    //允许请求的类型
    res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.setHeader("X-Powered-By",' 3.2.1')
    req.app.settings.trustProxy = true;
    if(req.method=="OPTIONS") res.sendStatus(200);
    else  next();
  });
/********
 * //解析参数
 */
// app.use(bodyParser());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
app.use(cors());



/********
 * 跨域
 * @type {http.Server}
 */
//allow custom header and CORS
app.all('*',function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.set('trust proxy', true);

/********
 * 路由
 */
routes(app);



/********
 *静态文件托管
 */
// app.use(express.static('public/images'));
// app.use(express.static('./public'));
// app.use("/public", express.static(path.resolve(__dirname, 'public')));

app.use('/public', express.static('E:/publics'));
app.use('/imgshow', express.static('E:/videos'));
// app.use('/videos', express.static('E:/videos'));

// 全局错误处理
process.on('uncaughtException', (error) => {
    console.error('未捕获的错误：', error);
    // 可以选择继续运行应用程序，或者执行一些清理操作后终止应用程序
});

process.on('unhandledRejection', (reason, promise) => {
    console.error('未处理的Promise rejection：', reason);
    // 可以选择继续运行应用程序，或者执行一些清理操作后终止应用程序
}); 
/********
 *开启服务
 */
var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('服务已经开启 骚年撸起来^^啊');
});